package com.apestech.framework.exec;

import com.apestech.framework.db.SqlSession;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.util.DateUtil;
import com.apestech.framework.util.FileUtil;
import com.apestech.framework.util.LocalVariable;
import com.apestech.framework.xml.plugin.modul.SpecialField;
import com.apestech.framework.xml.plugin.modul.SysCondition;
import com.apestech.framework.xml.pub.WriteXml;
import com.apestech.framework.xml.pub.core.ElementUtil;
import com.apestech.framework.xml.table.modul.MasterTable;
import com.apestech.framework.xml.table.modul.Tables;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.Date;

/**
 * @author hup
 * @create 2018-12-29-16:14
 */
public class MasterTableData extends ElementUtil {
    private Tables table;
    private String id;
    private String sql;
    private MasterTable.SubTable tab;
    private Element node;
    private SqlSession session;
    private SysCondition sysCondition;
    private String primary;

    public MasterTableData(String id, Tables table, SqlSession session) throws Exception {
        this.table=table;
        this.id=id;
        this.session=session;
        sysCondition=LocalVariable.getConfig().getSysCondition(session);
    }

    private  String getTableId(String key) {
        if(tab.getId().equals(key)){
            if(tab.getName()!=null) return tab.getName();
            else return table.getTable(key).getTabName();
        }
        if(tab.getSubTable(key).getName()!=null) return tab.getSubTable(key).getName();
        return table.getTable(key).getTabName();
    }

    public String getSql() {
        return sql;
    }

    public void setTab(MasterTable.SubTable tab) {
        this.tab = tab;
    }

    public Element getNode() {
        return node;
    }

    public void setNode(Element node) {
        this.node = node;
    }

    public void getDataStr() throws Exception {
        sql="";
        Tables.Table t=table.getTable(id);
        ArrayList<Tables.Field> flist=t.getFields();
        int len=flist.size();
        for(int i=0; i<len; i++){
            String fid=flist.get(i).getId();
            if(!"".equals(sql)) sql=sql+",";
            sql=sql+"\""+fid+"\":"+"\" "+"\"";
        }
        if(tab.getSubTable()!=null){
            ArrayList<String> klist=tab.getSubTable().getOrderKeylist();
            len=klist.size();
            for(int i=0; i<len; i++){
                String key=klist.get(i);
                MasterTableData tdata=new MasterTableData(key, table, session);
                tdata.setTab(tab.getSubTable(key));
                tdata.getDataStr();
                if(!"".equals(sql)) sql=sql+",";
                sql=sql+"\""+getTableId(key)+"\":"+"[{"+tdata.getSql()+"}]";
            }
        }
    }

    public void getDataXml() throws Exception {
        WriteXml xml=null;
        if(node==null) {
            xml=new WriteXml();
            xml.createXml();
            node=xml.getRoot();
        }
        Date date=new Date();
        String sid=session.getSpecialField().getOperateId();
        if(session.getTheme()!=null) sid=session.getTheme()+"."+sid;
        Object person= sysCondition.getIdData(sid, 0);
        String tabName=getTableId(id);
        Tables.Table t=table.getTable(id);
        ArrayList<Tables.Field> flist=t.getFields();
        int len=flist.size();
        int rlen=getRowCount(tabName, flist);
        for(int r=0; r<rlen; r++){
            Element ele=node.addElement(tabName);
            for(int i=0; i<len; i++){
                String fid=flist.get(i).getId();
                if(primary==null || (","+primary+",").indexOf(","+fid+",")<0){
                    Object value=getValue(fid, date, person, r);
                    if(value!=null) ele.addAttribute(fid, castToString(value));
                    else {
                        if(flist.get(i).getDefaultValue()!=null) ele.addAttribute(fid, flist.get(i).getDefaultValue());
                        else ele.addAttribute(fid, "");
                    }
                }
            }
            if(len==0){
                Table dtable=session.getDictTable(tabName);
                if(dtable==null) throw new Exception("当前表名["+tabName+"]不合法！");
                String cols=dtable.getColumn();
                if(cols.indexOf(",")<0) ele.addAttribute(cols, "");
                else {
                    String[] clist=cols.split(",");
                    len=clist.length;
                    for(int i=0; i<len; i++){
                        String fid=clist[i];
                        if(!"".equals(fid)) ele.addAttribute(fid, "");
                    }
                }
            }
            if(tab.getSubTable()!=null){
                ArrayList<String> klist=tab.getSubTable().getOrderKeylist();
                len=klist.size();
                for(int i=0; i<len; i++){
                    String key=klist.get(i);
                    MasterTableData tdata=new MasterTableData(key, table, session);
                    tdata.setTab(tab.getSubTable(key));
                    tdata.setNode(ele);
                    tdata.getDataXml();
                }
            }
        }
        if(xml!=null){
            String dir=LocalVariable.getTempDir();
            String source=dir+"data\\"+table.getMasterTable()+".xml";
            String dest=dir+"data_man\\"+table.getMasterTable()+".xml";
            xml.writeXml(source);
            if(!FileUtil.isFileExist(dest)) FileUtil.copyFile(source, dest);
        }
    }

    private int getRowCount(String tabName, ArrayList<Tables.Field> flist) throws Exception {
        int row=1;
        if(table.getMasterTable().equals(tabName)) row=1;
        else {
            if(primary==null){
                primary=table.getParentTablePrimary(id);
                if(primary==null) primary="";
            }
            int len=flist.size();
            for(int i=0; i<len; i++){
                String fid=flist.get(i).getId();
                if(sysCondition.getIdData(fid, 0)!=null){
                    row=sysCondition.getRow();
                    break;
                }
            }
        }
        return row;
    }

    private Object getValue(String id, Date date, Object person, int rowinx) throws Exception {
        Object value=null;
        SpecialField.Field f=session.getSpecialField();
        if(id.equals(f.getStartDate())) value=DateUtil.getStartDateStr(date, 0);
        else if(id.equals(f.getEndDate())) value=DateUtil.getEndDateStr(date, 7);
        else if(id.equals(f.getCreateId()) || id.equals(f.getUpdateId()) ) value= person;
        else if(id.equals(f.getCreateDate()) || id.equals(f.getUpdateDate()) ) value=DateUtil.dateTimeToStr(date);
        else if(id.equals(f.getTimestamp()) ) value=DateUtil.dateTimeToStr(date);
        else{
            String sid=id;
            if(session.getTheme()!=null) sid=session.getTheme()+"."+id;
            value=sysCondition.getIdData(sid, rowinx);
        }
        return value;
    }

}
